package com.yunfeisoft.base.service.impl;

import com.yunfeisoft.base.dao.inter.WorkflowStepDao;
import com.yunfeisoft.base.dao.inter.WorkflowStepUserDao;
import com.yunfeisoft.base.model.WorkflowStep;
import com.yunfeisoft.base.model.WorkflowStepUser;
import com.yunfeisoft.base.service.inter.WorkflowStepService;
import com.yunfeisoft.common.base.BaseServiceImpl;
import com.yunfeisoft.common.utils.Page;
import com.yunfeisoft.utils.WorkflowHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * ClassName: WorkflowStepServiceImpl
 * Description: 流程步骤定义service实现
 * Author: Jackie liu
 * Date: 2020-01-03
 */
@Service("workflowStepService")
public class WorkflowStepServiceImpl extends BaseServiceImpl<WorkflowStep, String, WorkflowStepDao> implements WorkflowStepService {

    @Autowired
    private WorkflowStepUserDao workflowStepUserDao;
    @Autowired
    private WorkflowHelper workflowHelper;

    @Override
    public Page<WorkflowStep> queryPage(Map<String, Object> params) {
        return getDao().queryPage(params);
    }

    @Override
    public int removeByWorkflowDefineId(String workflowDefineId) {
        return getDao().removeByWorkflowDefineId(workflowDefineId);
    }

    @Override
    public List<WorkflowStep> queryByWorkflowDefineId(String workflowDefineId) {
        return getDao().queryByWorkflowDefineId(workflowDefineId);
    }

    @Override
    public List<WorkflowStepUser> getNextStepExecutor(String workflowDefineId, int currentStepNum) {
        return workflowHelper.getNextStepExecutor(workflowDefineId, currentStepNum);
    }

    @Override
    public int batchSave(List<WorkflowStep> list) {
        String workflowDefineId = list.get(0).getWorkflowDefineId();
        workflowStepUserDao.removeByWorkflowDefineId(workflowDefineId);
        getDao().removeByWorkflowDefineId(workflowDefineId);

        List<WorkflowStepUser> userList = new ArrayList<>();
        int result = super.batchSave(list);
        for (WorkflowStep workflowStep : list) {
            for (String userId : workflowStep.getUserIds()) {
                WorkflowStepUser workflowStepUser = new WorkflowStepUser();
                workflowStepUser.setUserId(userId);
                workflowStepUser.setWorkflowStepId(workflowStep.getId());
                userList.add(workflowStepUser);
            }
        }
        workflowStepUserDao.batchInsert(userList);
        return result;
    }
}